import { h } from 'vue'

function renderVirtual(swiperRef, slides, virtualData) {
  if (!virtualData) return null
  const getSlideIndex = (index) => {
    let slideIndex = index
    if (index < 0) {
      slideIndex = slides.length + index
    } else if (slideIndex >= slides.length) {
      // eslint-disable-next-line
      slideIndex = slideIndex - slides.length
    }
    return slideIndex
  }
  const style = swiperRef.value.isHorizontal()
    ? {
        [swiperRef.value.rtlTranslate ? 'right' : 'left']:
          `${virtualData.offset}px`
      }
    : {
        top: `${virtualData.offset}px`
      }
  const { from, to } = virtualData
  const loopFrom = swiperRef.value.params.loop ? -slides.length : 0
  const loopTo = swiperRef.value.params.loop ? slides.length * 2 : slides.length
  const slidesToRender = []
  for (let i = loopFrom; i < loopTo; i += 1) {
    if (i >= from && i <= to && slidesToRender.length < slides.length) {
      slidesToRender.push(slides[getSlideIndex(i)])
    }
  }
  return slidesToRender.map((slide) => {
    if (!slide.props) slide.props = {}
    if (!slide.props.style) slide.props.style = {}
    slide.props.swiperRef = swiperRef
    slide.props.style = style
    if (slide.type) {
      return h(
        slide.type,
        {
          ...slide.props
        },
        slide.children
      )
    } else if (slide.componentOptions) {
      return h(
        slide.componentOptions.Ctor,
        {
          ...slide.props
        },
        slide.componentOptions.children
      )
    }
  })
}

export { renderVirtual }
